﻿using AutoMapper;
using EquipmentModule.Contracts;
using EquipmentModule.Entity;
using EquipmentModule;
using EquipmentModule.ViewModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.IO;
using NPOI.OpenXmlFormats.Dml.Chart;

namespace EquipmentModule.Controllers
{
    /// <summary>
    /// 设备历史记录
    /// </summary>
    [ApiController]
    [Route("Equipment/[controller]")]
    public class HistoryController : ControllerBase
    {
        private readonly ILogger _logger;

        private readonly IWebHostEnvironment _env;
        private readonly IEquipmentHistoryService _service;
        private readonly IMapper _mapper;
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="env"></param>
        /// <param name="service"></param>
        public HistoryController(IMapper mapper,ILogger<HistoryController> logger, IWebHostEnvironment env, IEquipmentHistoryService service)
        {
            _logger = logger;
            _env = env;
            _service = service;
            _mapper = mapper;
        }
        /// <summary>
        /// 获取开始-结束时间内devId的历史数据
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束数据</param>
        /// <param name="devId">设备Id</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Index(DateTime start,DateTime end,string devId)
        {
            string db = Common.GetHeader4DB(this.Request);
            var data = _service.Index(start, end, devId,db).ToList();
            List<EquipmentHistoryViewModel> models = new List<EquipmentHistoryViewModel>();
            if (data.Count>0)
            {
                data = data.OrderBy(x => x.TagName).ToList();
                foreach (var item in data)
                {
                    EquipmentHistoryViewModel model = models.Find(x => x.Name == item.TagName);
                    if (model==null)
                    {
                        model = new EquipmentHistoryViewModel() { Name = item.TagName, Value = new List<List<string>>() {
                            new List<string>(){ $"{item.CreateTime}", $"{item.Value}" }
                        } };
                        models.Add(model);
                    }
                    else
                    {
                        model.Value.Add(new List<string> { $"{item.CreateTime}",$"{item.Value}"});
                    }
                }
            }
            return Ok(new ResponseData(null, models));
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="re"></param>
        /// <param name="id">设备Id</param>
        /// <returns></returns>
        [HttpPost("Upload/{id}")]
        public IActionResult Import([FromForm] IFormCollection re,[FromRoute]Guid id)
        {
            string db = Common.GetHeader4DB(this.Request);
            var files = re.Files;
            //Console.WriteLine(_env.ContentRootPath);
            foreach (var af in files)
            {
                if (af.Length < 1) break;
                string fileName = null;
                if (af.FileName.EndsWith("xls")||af.FileName.EndsWith("xlsx"))
                {
                    fileName = Path.Combine(_env.ContentRootPath,"Import",af.FileName);
                    if (System.IO.File.Exists(fileName))
                    {
                        System.IO.File.Delete(fileName);
                    }
                    using var fs = new FileStream(fileName,FileMode.Create);
                    af.CopyTo(fs);
                }
                if (!string.IsNullOrEmpty(fileName))
                {
                    _service.ImportHistoryData2DB(fileName,id, db);
                }
            }
            return Ok(new ResponseData(null, null));
        }


        [HttpGet("Carousel4Equipment")]
        public IActionResult Carousel4Equipment(Guid guid)
        {
            string db = Common.GetHeader4DB(this.Request);
            var data = _service.Carousel4Equipment(guid, db);
            return Ok(new ResponseData(null, data));
        }

        [HttpGet("Carousel4EquipmentId")]
        public IActionResult Carousel4EquipmentId()
        {
            string db = Common.GetHeader4DB(this.Request);
            List<Guid> data = _service.Carousel4EquipmentId(db);
            return Ok(new ResponseData(null, data));
        }

    }
}
